using Game.Networking.Utils;
using UnityEngine;

namespace Game.UI {
	public sealed class SettingsWindow : UIWindow {
		const string SoundParamPrefsKey = "settings_sound";
		public Checkbox SoundCheckbox;

		IComputingUnitUserDataProvider _dataProvider;

		bool SoundOnOff {
			get {
				return PlayerPrefs.GetInt(SoundParamPrefsKey, 1) == 1 ? true : false;
			}

			set {
				PlayerPrefs.SetInt(SoundParamPrefsKey, value ? 1 : 0);
				AudioListener.volume = value ? 1 : 0;
			}
		}

		protected override void Awake() {
			base.Awake();
			var soundEnabled = SoundOnOff;
			SoundCheckbox.SetupState(soundEnabled);
			AudioListener.volume = soundEnabled ? 1 : 0;
			SoundCheckbox.OnCheckboxClicked.Subscribe(this, OnSoundCheckboxChanged);
		}

		private void Start() {
			var isServer = NetworkOptions.StartServer;
			if ( isServer ) {
				_dataProvider = new ServerComputingUnitUserDataProvider();
			} else {
				_dataProvider = new ClientComputingUnitUserDataProvider();
			}
		}

		protected override void OnDestroy() {
			base.OnDestroy();
			SoundCheckbox?.OnCheckboxClicked?.Unsubscribe(OnSoundCheckboxChanged);
		}

		void OnSoundCheckboxChanged(bool state) {
			SoundOnOff = state;
		}
	}
}
